import regeneratorRuntime from './utils/runtime.js'
var globalData = {
  VERSION: 'v0.0.1',
  HOST: "https://zhufu.xingqiuribao.com",
  PROFILE_RECOVER_FLAG: 'http://zhufu.xingqiuribao.com',
  TOKEN: '',
  userInfo: null,
};
const wxGetImageInfo = (obj) => {
  return new Promise((resolve, reject) => {
    obj.success = function (res) { resolve(res) }
    obj.fail = function (res) { reject(res) }
    wx.getImageInfo(obj)//执行函数，obj为传入函数的参数
  })
}
var appConfig = {
  globalData: globalData,
  setGlobalData: function(name, value) {
    globalData[name] = value
    wx.setStorageSync(name, value)
  },
  getGlobalData : function(name){
    if (this.globalData[name]){
      return this.globalData[name]
    }else{
      return wx.getStorageSync(name)
    }
  },
  // 初始化App
  onLaunch: function(e) { },
  onLoad: function (options){
    let request = decodeURIComponent(options.query.q)
    if (request && request.startsWith(this.globalData.PROFILE_RECOVER_FLAG) &&
      request.length > this.globalData.PROFILE_RECOVER_FLAG.length + 6) {
      let code = request.substring(this.globalData.PROFILE_RECOVER_FLAG.length + 6)
      this.globalData.shareId = code
    }
    if (options.query && options.query.code) {
      this.globalData.shareId = options.query.code
    }
  },
  // 后台
  onHide: function() {
    console.log("-----onHide----");
  },
  /**
   * App 启动后执行
   */
  onShow: async function() {
    const _this = this;
    if (!globalData.userInfo) {
      this.getUserInfo()
    }
    let background = await wxGetImageInfo({ src: 'https://zhufu.xingqiuribao.com/draw.jpg'})
    _this.globalData.BACKGROUND = background.path
  },
  getUserInfo : function(call){
    const _this = this;
    wx.login({
      success: login => {
        wx.getUserInfo({
          success: async res => {
            let id = _this.getGlobalData('ID')
            _this.POST(`/api/user/login?id=${id}&code=${login.code}`, res.userInfo, async function (res) {
              _this.setGlobalData("ID", res.data.id)
              _this.setGlobalData("CODE", res.data.code)
            })
            let avarta = await wxGetImageInfo({ src: res.userInfo.avatarUrl })
            _this.globalData.AVARTA = avarta.path
            call && call.success && call.success(login, res)
            _this.setGlobalData('userInfo', res.userInfo)
          },
          fail: error => {
            call && call.fail && call.fail(error)
            wx.navigateTo({ url: '/pages/login/index' })
          }
        })
      },
      fail: error => {
        call && call.fail && call.fail(error)
        wx.navigateTo({ url: '/pages/login/index' })
      }
    })
  },
  /**
   * get请求
   */
  GET: function (url, data, success, fail, complete) {
    wx.showNavigationBarLoading();
    // 构造请求参数
    data = data || {};
    wx.request({
      url: globalData.HOST + url,
      header: { 'content-type': 'application/json' },
      data: data,
      dataType: 'json',
      success: function (res) {
        if (res.statusCode == 200) {
          if (res.data.success) {
            success && success(res.data);
          } else {
            appConfig.showError(res.data ? res.data.errMsg : '服务器错误', function () { fail && fail(res); });
          }
        } else {
          appConfig.showError(res.errMsg, function () { fail && fail(res); });
        }
      },
      fail: function (res) {
        appConfig.showError(res.errMsg, function () { fail && fail(res); });
      },
      complete: function (res) {
        wx.hideNavigationBarLoading();
        complete && complete(res);
      },
    });
  },
  /**
   * post提交
   */
  POST: function (url, data, success, fail, complete) {
    wx.showNavigationBarLoading();
    data = data || {}
    wx.request({
      url: globalData.HOST + url,
      header: { 'content-type': 'application/json' },
      method: 'POST',
      data: data,
      dataType: 'json',
      success: function (res) {
        if (res.statusCode == 200) {
          if (res.data.success) {
            success && success(res.data);
          } else {
            appConfig.showError(res.data ? res.data.errMsg : '服务器错误', function () { fail && fail(res); });
          }
        } else {
          appConfig.showError(res.errMsg, function () { fail && fail(res); });
        }
      },
      fail: function (res) {
        appConfig.showError(res.errMsg, function () { fail && fail(res); });
      },
      complete: function (res) {
        wx.hideNavigationBarLoading()
        complete && complete(res)
      }
    });
  },
  /**
  * 显示成功提示框
  */
  showSuccess: function (msg, callback) {
    if (!msg) { return; }
    wx.showModal({
      title: '友情提示',
      content: msg,
      icon: 'success',
      showCancel: false,
      success: function (res) {
        callback && callback();
      }
    });
  },
  /**
   * 显示失败提示框
   */
  showError: function (msg, callback) {
    if (!msg){ return; }
    wx.showModal({
      title: '友情提示',
      content: msg,
      showCancel: false,
      success: function (res) {
        callback && callback();
      }
    });
  },
}
App(appConfig)